<template>
	<div>
		<cl-drawer
			ref="drawer"
			:props="{
				title: title + '门店',
				appendToBody: true,
				size: '750px'
			}"
			show-confirm
			confirm-text="提交"
			@close="reset"
			@confirm="submit"
			:saving="saving"
		>
			<el-form
				ref="form"
				label-position="top"
				:disabled="saving"
				:model="form"
				:rules="rules"
			>
				<el-form-item label="基本信息">
					<el-card shadow="never">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="所属事业部" prop="biz_id">
									<cl-select
										v-model="form.biz_id"
										style="width: 100%"
										placeholder="请选择事业部"
										filterable
										:disabled="type == 'edit'"
										@change="bizChange"
									>
										<el-option
											v-for="item in business"
											:key="item.biz_id"
											:label="item.biz_name"
											:value="item.biz_id"
										/>
									</cl-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="门店名称" prop="dept_name">
									<el-input
										v-model="form.dept_name"
										placeholder="请输入门店名称"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="经营类型" prop="ctype">
									<cl-select
										v-model="form.ctype"
										style="width: 100%"
										placeholder="请选择经营类型"
									>
										<el-option
											v-for="item in $const.CTYPE_LIST"
											:key="item.value"
											:label="item.label2"
											:value="item.value"
										/>
									</cl-select>
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item prop="city_id">
									<template #label>
										城市
										<el-button
											type="text"
											icon="el-icon-circle-plus"
											@click="addCity()"
											style="height: 26px"
										>
											新增城市
										</el-button>
									</template>
									<cl-select
										v-model="form.city_id"
										style="width: 100%"
										placeholder="请选择城市"
										filterable
									>
										<el-option
											v-for="item in bizRefData.city"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										/>
									</cl-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item prop="war_zone_id" label="战区">
									<cl-cascader
										style="width: 100%"
										v-model="form.war_zone_id"
										@change=""
										:options="warZoneList"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item prop="hospital_id" label="医院">
									<cl-select
										v-model="form.hospital_id"
										style="width: 100%"
										placeholder="请选择医院"
										filterable
										clearable
									>
										<el-option :key="0" label="无" :value="0" />
										<el-option
											v-for="item in hospitalList"
											:key="item.dept_id"
											:label="item.dept_name"
											:value="item.dept_id"
										/>
									</cl-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="预约时长" prop="cart_duration">
									<cart-duration v-model="form.cart_duration" style="width: 100%" />
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item label="看板备注" prop="remark">
									<el-input
										v-model="form.remark"
										placeholder="请输入看板备注"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item label="门店Logo/照片" prop="log">
									<cl-upload v-model="form.log" />
									<div class="tips">建议尺寸200x200px</div>
								</el-form-item>
							</el-col>

							<!-- <el-col :span="12">
								<el-form-item label="区域" prop="region_ids">
									<cl-select
										v-model="form.region_ids"
										style="width: 100%"
										placeholder="请选择区域"
										filterable
									>
										<el-option
											v-for="item in bizRefData.region"
											:key="item.id"
											:label="item.name"
											:value="item.id"
										/>
									</cl-select>
								</el-form-item>
							</el-col> -->
							<el-col :span="12">
								<el-form-item label="经营状态" prop="bus_state">
									<cl-select
										v-model="form.bus_state"
										style="width: 100%"
										placeholder="请选择经营状态"
										filterable
									>
										<el-option label="营业" :value="1" />
										<el-option label="停业" :value="2" />
									</cl-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="营业时间" prop="office_time">
									<div class="flex">
										<el-time-select
											placeholder="起始时间"
											v-model="form.btime"
											:clearable="false"
											:picker-options="{
												start: '00:00',
												step: '00:30',
												end: '23:30'
											}"
											@change="changeBtime"
										>
										</el-time-select>
										<span style="margin: 0 6px">~</span>
										<el-time-select
											ref="etime"
											placeholder="结束时间"
											v-model="form.etime"
											:clearable="false"
											:picker-options="{
												start: '00:00',
												step: '00:30',
												end: '23:30',
												minTime: form.btime
											}"
										>
										</el-time-select>
									</div>
								</el-form-item>
							</el-col>
							<el-col />
							<el-col :span="8">
								<el-form-item label="所在地区" prop="region">
									<cl-cascader
										v-model="form.region"
										:options="addressLevel"
										placeholder="请选择所在地区"
										style="width: 100%"
										@change="regionChange"
										filterable
									/>
								</el-form-item>
							</el-col>
							<el-col :span="16">
								<el-form-item label="详细地址" prop="addr">
									<!-- <el-input v-model="form.addr" placeholder="请输入详细地址" /> -->
									<div class="flex">
										<el-autocomplete
											ref="tipinput"
											class="tipinput mr-1"
											popper-class="tipinput-autocomplete"
											style="flex: 1"
											v-model="form.addr"
											:fetch-suggestions="querySearchAddr"
											@select="handleSelectAddr"
											placeholder="请输入关键字搜索"
										>
											<template slot-scope="{ item }">
												<div class="tipinput-autocomplete__item">
													<div class="ellipsis name">{{ item.name }}</div>
													<span class="addr">{{ item.address }}</span>
												</div>
											</template>
										</el-autocomplete>
										<el-button type="primary" @click="handleClickSearchAddr">
											搜索地图
										</el-button>
									</div>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="经度" prop="longitude">
									<el-input v-model="form.longitude" placeholder="请输入经度" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="纬度" prop="latitude">
									<el-input v-model="form.latitude" placeholder="请输入纬度" />
								</el-form-item>
							</el-col>
							<el-col>
								<div class="amap-box">
									<el-amap v-bind="amapOptions">
										<el-amap-marker
											v-if="amapMarker.position"
											v-bind="amapMarker"
											:z-index="150"
											vid="marker"
										/>
									</el-amap>
								</div>
							</el-col>
						</el-row>
					</el-card>
				</el-form-item>

				<el-form-item label="房间配置">
					<el-card shadow="never">
						<el-card
							shadow="never"
							v-for="(item, index) in form.rooms"
							:key="item.key"
							class="mb-2"
						>
							<div class="flex">
								<cl-flex1 class="flex flex-align-center">
									<cl-avatar :src="logo" shape="square" size="medium" preview />
									<h3 class="ml-1">房间({{ index + 1 }})</h3>
								</cl-flex1>
								<div>
									<el-button type="primary" @click="handleDelRoom(row)">
										删除
									</el-button>
								</div>
							</div>
							<div class="flex flex-wrap mt-1">
								<icon-svg
									v-for="n in item.num"
									:key="n"
									name="icon-bed"
									:size="36"
									class="mr-2"
								/>
							</div>
							<bed-num class="pt-1" v-model="item.num" />
						</el-card>
						<div class="flex flex-justify-center">
							<el-button
								type="primary"
								size="small"
								style="width: 200px"
								@click="handleAddRoom"
							>
								添加
							</el-button>
						</div>
					</el-card>
				</el-form-item>
			</el-form>
		</cl-drawer>
		<cl-city-form ref="cityForm" @confirm="getCityList" />
	</div>
</template>
<script>
import BedNum from "./bed-num";
import CartDuration from "@/components/cart-duration.vue";
import { validate } from "@/utils/validate";
import threeLevel from "@/assets/countryLevel3";
import { debounce } from "cl-admin/utils";
import { deepSearch, uuid } from "@/utils";
import dayjs from "dayjs";
import { AMapManager } from "vue-amap";
const amapManager = new AMapManager();

export default {
	name: "cl-shop-form",
	components: {
		BedNum,
		CartDuration
	},
	data() {
		const validateOfficeTime = (rule, value, callback) => {
			const { btime, etime } = this.form;
			if (!btime) {
				return callback(new Error("请选择营业开始时间"));
			}
			if (!etime) {
				return callback(new Error("请选择营业结束时间"));
			}
			callback();
		};
		const appointTimeValidator = (rule, value, callback) => {
			const { day } = this.activeForm;
			if (day * 1 > 5) {
				return callback(new Error("持续时长不能大于5天"));
			}
			return callback();
		};
		return {
			addressLevel: threeLevel,
			amap: null,
			amapGeo: null,
			amapOptions: {
				vid: "shop_amap",
				ref: "amap",
				amapManager,
				center: [118.178906, 24.462187],
				zoom: 11,
				events: {
					init: o => {
						this.amap = o;
					},
					mapmove: () => this.mapMove()
				},
				plugin: [
					{ pName: "ToolBar" },
					{
						pName: "Geolocation",
						buttonPosition: "RB",
						zoomToAccuracy: false,
						events: {
							init: o => {
								this.amapGeo = o;
								// const { longitude, latitude } = this.form;
								// if (longitude?.length && latitude?.length) return;
								// // 获取用户当前的精确位置信息
								// o.getCurrentPosition((status, result) => {
								// 	if (result && result.position) {
								// 		// const { province } = result.addressComponent || {}
								// 		const { lng, lat } = result.position;
								// 		this.amapOptions.center = [lng, lat];
								// 	}
								// });
							}
						}
					}
				]
			},
			amapMarker: {
				position: null,
				draggable: true,
				events: {
					dragend: e => {
						const { lng, lat } = e.lnglat;
						this.amapOptions.center = [lng, lat];
						this.form.longitude = lng;
						this.form.latitude = lat;
					}
				}
			},
			amapAutoComplete: null,
			form: {
				dept_id: "",
				dept_name: "", // 门店名称
				parent_id: 0, // 父级id
				biz_id: "", //事业部id
				ctype: 1, //经营类型 1：直营，2：加盟
				region: [], //所属地区
				province: "", //省id
				city: "", //市id
				area: "", //区id
				addr: "", //详细地址
				longitude: "", //经度
				latitude: "", //纬度
				city_id: "", //绑定城市
				bus_state: 1, // 经营状态
				region_ids: "",
				region_manager_id: "",
				city_manager_id: "",
				log: "",
				rooms: [],
				btime: "10:00",
				etime: "20:00",
				cart_duration: "",
				war_zone_id: "",
				remark: "",
				hospital_id: ""
			},
			rules: {
				dept_name: [{ required: true, message: "请填写门店名称" }],
				biz_id: [{ required: true, message: "请选择事业部" }],
				ctype: [{ required: true, message: "请选择经营类型" }],
				bus_state: [{ required: true, message: "请选择经营状态" }],
				region: [{ required: true, message: "请选择所在地区" }],
				city_id: [{ required: true, message: "请选择城市" }],
				addr: [{ required: true, message: "请填写详细地址" }],
				longitude: [
					{ required: true, message: "请填写经度" },
					{ pattern: validate.longitude, message: "经度格式不正确" }
				],
				latitude: [
					{ required: true, message: "请填写纬度" },
					{ pattern: validate.latitude, message: "纬度格式不正确" }
				],
				region_ids: [{ required: true, message: "请选择区域" }],
				office_time: [{ required: true, validator: validateOfficeTime }],
				// beds: [
				// 	{ required: true, message: "请填写房间床位数" },
				// 	{ type: "integer", min: 1, message: "房间床位数不能为0" }
				// ]
			},
			saving: false,
			type: "add",
			accountsVisible: false,
			activeForm: {
				begin_time: "",
				day: 1,
				teacher_num: ""
			},
			activeRules: {
				begin_time: [{ required: true, message: "请选择开始时间" }],
				day: [{ required: true, validator: appointTimeValidator }],
				teacher_num: [{ required: true, message: "请填写数量" }]
			},
			actvieType: "add",
			pickerOptions: {
				disabledDate: time => {
					return dayjs(time).isBefore(dayjs(), "date");
				}
			},
			cityList: [],
			warZoneList: [],
			hospitalList: [],
		};
	},
	computed: {
		//事业部
		title() {
			let title = "";
			switch (this.type) {
				case "add":
					title = "新增";
					break;
				case "edit":
					title = "修改";
					break;
				case "copy":
					title = "复制";
					break;
			}
			return title;
		},
		bizRefData() {
			const { biz_id } = this.form;
			return this.getBizRefData(biz_id);
		},
		refBiz() {
			const { biz_id } = this.form;
			return this.business.find(v => v.biz_id == biz_id) || {};
		},
		logo() {
			const { log } = this.form;
			const { biz_logo } = this.refBiz;
			return log || biz_logo || "";
		}
	},
	created() {
		this.form.biz_id = this.getCurrBiz(false);
	},
	methods: {
		async open(type = "add", data = {}) {
			this.type = type;
			this.$refs.drawer.create(async () => {
				if (type != "add") {
					await this.getDetail(data);
				}
				if (!this.form.log) {
					this.form.log = "";
				}
				console.log("shop form", this.form);
				setTimeout(() => {
					this.getCurrPosition();
				}, 300);
				this.init();
				// this.getParentList();
			});
		},
		async init() {
			this.getCityList();
			this.getWarZone();
			this.getHospital();
		},
		// getParentList() {
		// 	const { biz_id } = this.form;
		// 	this.$service.region.getParentList({ biz_id }).then(res => {
		// 		console.log(res);
		// 		this.cityList = res.map(item => {
		// 			let newItem = {
		// 				id: item.id,
		// 				value: item.id,
		// 				label: item.name,
		// 				parent_id: item.parent_id
		// 			};
		// 			if (item.children && item.children.length) {
		// 				newItem.children = item.children.map(it => {
		// 					let newit = {
		// 						id: it.id,
		// 						value: it.id,
		// 						label: it.name,
		// 						parent_id: it.parent_id
		// 					};
		// 					if (it.children && it.children.length) {
		// 						newit.children = it.children.map(its => {
		// 							return {
		// 								id: its.id,
		// 								value: its.id,
		// 								label: its.name,
		// 								parent_id: its.parent_id
		// 							};
		// 						});
		// 					}

		// 					return newit;
		// 				});
		// 			}
		// 			return newItem;
		// 		});
		// 	});
		// },
		cityChange(data) {
            this.form.region_ids = data[0]
			this.form.region_manager_id= data[1] || 0
			this.form.city_manager_id= data[2] || 0
		},
		getCurrPosition() {
			const { longitude, latitude } = this.form;
			if (longitude?.length && latitude?.length) return;
			this.amapGeo?.getCurrentPosition?.((status, result) => {
				// console.log("getCurrentPosition", { status, result });
				if (result && result.position) {
					// const { province } = result.addressComponent || {}
					const { lng, lat } = result.position;
					let center = [lng, lat];
					// console.log("center", center);
					this.amapOptions.center = center;
				}
			});
		},

		async getDetail({ dept_id }) {
			const res = await this.$service.shop.single({ dept_id });
			Object.keys(this.form).forEach(key => {
				res[key] != undefined && (this.form[key] = res[key]);

			});
			if(res.region_ids !== 0 && res.region_manager_id !== 0 && res.city_manager_id !== 0){
			 }

			const { province, city, area, beds } = res;
			if (province || city || area) {
				this.form.region = [province, city, area];
			}
			this.form.rooms = (beds || []).map(v => {
				return {
					key: uuid(),
					num: (v || 0) * 1
				};
			});
			let position = [(res.longitude ?? 0) * 1, (res.latitude ?? 0) * 1];
			this.amapOptions.center = position;
			this.amapMarker.position = position;
		},
		close() {
			this.$refs.drawer.close();
		},
		reset() {
			this.saving = false;
			this.$resetFields({ ...this.form }, ["parent_id", "biz_id"]);
			this.form.ctype = 1;
			this.form.bus_state = 1;
			this.form.btime = "10:00";
			this.form.etime = "20:00";
			this.$refs.form.resetFields();
			this.amapMarker.position = null;
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				this.saving = true;
				const { biz_id, rooms, ...args } = this.form;
				let form = {
					...args,
					biz_id,
					beds: rooms.map(v => v.num)
				};
				let editing = this.type == "edit";
				await this.$service.shop[editing ? "update" : "add"](form).done(() => {
					this.saving = false;
				});
				this.$message.success("操作成功");
				this.$emit("confirm", biz_id, !editing);
				this.close();
				await this.getBizRefShop(biz_id);
			});
		},
		// 事业部
		bizChange(v) {
			this.form = {
				...this.form,
				city_id: "",
				region_ids: []
			};
			this.getCityList();
			this.getWarZone();
			this.getHospital();
		},
		//获取城
		async getCityList() {
			const { biz_id } = this.form;
			this.getBizRefCity(biz_id);
		},
		async getWarZone() {
			const { biz_id } = this.form;
			const data = await this.$service.dept.filtrate({biz_id: biz_id, post: 7})
			let warZonelist =
				data?.map((item) => {
					let newItem = {
						id: item.dept_id,
						value: item.dept_id,
						label: item.dept_name,
						children: []
					};
					if (item.children && item.children.length) {
						newItem.children = item.children
							.filter((subItem) => subItem.parent_id == item.dept_id)
							.map((subItem) => {
								return {
									id: subItem.dept_id,
									value: subItem.dept_id,
									label: subItem.dept_name
								};
							});
					}
					return newItem;
				}) ?? [];

			this.warZoneList = warZonelist
		},
		async getHospital() {
			const { biz_id } = this.form;
			const data = await this.$service.dept.filtrate({biz_id: biz_id, post: 8})
			this.hospitalList = data[0]['children']
		},
		//地区

		addCity(editing = false, data = {}) {
			const { biz_id } = this.form;
			this.$refs.cityForm.open(editing, data, biz_id);
		},

		mapMove: debounce(function() {
			if (!this.$refs.amap) return;
			let center = this.$refs.amap.$$getCenter();
			this.amapOptions.center = center;
		}, 300),
		regionChange(v) {
			this.form.province = v[0]; //省
			this.form.city = v[1]; //市
			this.form.area = v[2]; //区
			let city = deepSearch(threeLevel, v[1], "value").label;
			this.form.addr = "";
			this.amapMarker.position = null;
			this.amapAutoComplete = new AMap.Autocomplete({ city });
		},
		// 点击搜索地址
		handleClickSearchAddr() {
			this.$refs.tipinput.focus();
		},
		handleSelectAddr(item) {
			this.form.addr = item.name;
			this.amapOptions.center = item.position;
			this.form.longitude = item.position[0];
			this.form.latitude = item.position[1];
			this.amapMarker = {
				...this.amapMarker,
				position: item.position,
				info: item
			};
			// placeSearch.setCity(item.adcode);
			// placeSearch.search(item.name); //关键字查询查询
		},
		// 地址查询
		querySearchAddr(kerword, cb) {
			if (!kerword || !this.amapAutoComplete) return cb([]);
			this.amapAutoComplete.search(kerword, (status, result) => {
				if (status == "complete" && result.info == "OK") {
					let list = result.tips
						.filter(v => v.location)
						.map(v => ({
							...v,
							position: [v.location.lng, v.location.lat]
						}));
					cb(list);
					return;
				}
				cb([]);
			});
		},
		// 添加房间
		handleAddRoom() {
			this.form.rooms.push({
				key: uuid(),
				num: 1
			});
		},
		handleDelRoom(index) {
			this.form.rooms.splice(index, 1);
		},
		// 营业开始时间改动
		changeBtime() {
			this.$refs.etime?.focus?.();
			if (!this.form.btime || !this.form.etime) return;
			let date = dayjs().format("YYYY-MM-DD");
			let btime = dayjs(date + " " + this.form.btime);
			let etime = dayjs(date + " " + this.form.etime);
			let diff = etime.diff(btime);
			if (diff > 0) return;
			this.form.etime = "";
		},

		addActive() {
			this.resetActiveForm();
			this.actvieType = "add";
			this.accountsVisible = true;
		},
		// deleteActive(index) {
		// 	this.form.activity_list.splice(index, 1);
		// },
		editActive(row) {
			this.actvieType = "edit";
			this.activeForm = { ...row };
			this.accountsVisible = true;
		},
		submitActive() {
			this.$refs.activeform.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				this.resetActiveForm();
				this.accountsVisible = false;
			});
		},
		resetActiveForm() {
			this.activeForm = {
				begin_time: "",
				day: 1,
				teacher_num: ""
			};
		}
	}
};
</script>

<style lang="scss" scoped>
.tipinput-autocomplete {
	&__item {
		line-height: normal;
		padding: 4px 0;
		.addr {
			font-size: 12px;
			color: #b4b4b4;
		}
	}
}
.tips {
	color: #909399;
	font-size: 12px;
	line-height: 1.5;
}
.amap-box {
	height: 350px;
}
.rooms-logo {
	::v-deep .el-upload {
		border-radius: 3px;
		.cl-upload__cover--action i {
			font-size: 16px !important;
		}
	}
}
</style>
